<template>
  <el-card class="box-card">
    <template v-for="item in CategoryListAll" :key="item.id">
      <div class="text">
        <span class="cur">
          <el-checkbox v-model="item.checked" @change="(val) => handleCheckAllChange(val, item)">{{ item.name }}
          </el-checkbox>
        </span>
      </div>
      <div class="lit">
        <el-checkbox v-for="el in item.children" v-model="el.checked" :value="el.name" size="large" :key="el.id">
          {{ el.name }}
        </el-checkbox>
      </div>
    </template>
    <div style="text-align: center">
      <el-button type="primary" @click="confirm">保存</el-button>
      <el-button @click="clear">清空</el-button>
    </div>
  </el-card>
</template>
  
<script setup lang='ts'>
import { computed, ref, watch } from 'vue';
import * as http from '@/request/api'
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/theme-chalk/index.css';
import { useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
let checkeList = [] as number[]

const CategoryListAll = ref<ICategoryListAllRes[]>([])
async function ResData() {
  try {
    let res = await Promise.all([http.admin.ResourceCategoryListAll(), http.admin.ResourceListAll(), http.admin.RoleListResource(Number(route.query.id))])
    // res数组[第一个参数返回结果，第二个参数返回结果]
    // 处理全选

    res[0].data.map(item => {
      item.children = [];
      item.checked = false;
    })

    res[2].data.map(item => {
      checkeList.push(item.id)
      res[1].data.forEach(el => {
        if (el.id === item.id) {
          el.checked = true
        }
      })
    })

    res[0].data.map(item => {
      let newArr = res[1].data.filter(el => el.categoryId === item.id)
      item.children = newArr
    })
    CategoryListAll.value = res[0].data
    console.log(CategoryListAll.value);

  } catch (err: any) {
    ElMessage({
      message: '获取数据失败',
      type: 'error',
    })
  }
}
ResData()

const handleCheckAllChange = (val: any, item: ICategoryListAllRes) => {
  item.children?.map(item => item.checked = val)
}

// 全选
watch(
  () => CategoryListAll.value.map(item => item.children),
  (val) => {
    // 发送请求参数
    CategoryListAll.value.map(item => {
      item.children?.map(el => {
        if (el.checked) {
          checkeList.push(el.id)
          checkeList = [...new Set(checkeList)]
        }
        else {
          let index = checkeList.findIndex(ind => ind === el.id)
          if (index > -1) {
            checkeList.splice(index, 1)
          }
        }
      })
      if (item.children?.every(el => el.checked) && item.children.length) {
        item.checked = true
      } else {
        item.checked = false
      }
    })
  },
  { deep: true }
)

// 保存
function confirm() {
  ElMessageBox.confirm(
    '你确定保存当前角色资源吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      let roleAllocRes = await http.admin.RoleAllocResource({ roleId: Number(route.query.id), resourceIds: checkeList.join(',') })
      router.push('role')

      ElMessage({
        type: 'success',
        message: '分配成功',
      })
    })
    .catch(() => { })
}
// 清除
function clear() {
  CategoryListAll.value.map(item => {
    item.children?.map(el => el.checked = false)
  })
}
// let form = computed({
//   get: () => CategoryListAll.value,
//   set: (val) => {

//     return CategoryListAll.value.map(item => {
//       console.log(item.children);

//       if (item.children?.every(el => el.checked)) {
//         item.checked = true
//         console.log(1111111);

//       } else {
//         item.checked = false
//       }
//       return item
//     })
//   },
// })
</script>
  
<style scoped>
.box-card {
  margin: 10px;
  box-sizing: border-box;
  margin-top: 20px;
}

.box-card div:nth-child(n) {
  border-radius: 3px;
  padding: 20px;
}

.text {
  background-color: rgb(242, 246, 252);
}

.lit {
  display: flex;
  flex-wrap: wrap;
}

:deep(.el-checkbox__label) {
  width: 320px;
}
</style>